package com.yuqiaotech.zcj.dao.impl;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.yuqiaotech.zcj.dao.GenericDao;


public class GenericDaoHibernate<T, PK extends Serializable>
extends HibernateDaoSupport
implements GenericDao<T, PK> {

	private Class<T> entityClass;
	
	public GenericDaoHibernate(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	public void delete(T entity) {
		this.getHibernateTemplate().delete(entity);
	}

	public List findByHql(String hql, Object... params) {
		return getHibernateTemplate().find(hql, params);
	}

	public T get(PK id) {
		return (T) getHibernateTemplate().get(entityClass, id);
	}

	public T save(T entity) {
		return (T) getHibernateTemplate().merge(entity);
	}

	public Object findUniqueBy(Class persistentClass,String propertyName, Object value) {
		Criteria criteria = getSession().createCriteria(persistentClass);
		return criteria.add(Restrictions.eq(propertyName, value)).uniqueResult();
	}

	public List findByCriteria(
			final DetachedCriteria detachedCriteria) {
		return (List) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Criteria criteria = detachedCriteria
								.getExecutableCriteria(session);
						List items = criteria.list();
						return items;
					}
				});
	}
	
	/**
	 * 执行更新操作的hql。
	 * @param hql
	 * @param params
	 * @return
	 */
	public int executeUpdate(String hql, Object ... params){
		return this.getHibernateTemplate().bulkUpdate(hql, params);
	}

	@Override
	public void update(T entity) {
		// TODO Auto-generated method stub
		getHibernateTemplate().update(entity);
	}
}
